var db           = require('../../config/mongo_database');
var redisClient  = require('../../config/redis_database').redisClient;
var tokenManager = require('../../config/token_manager');
var logger       = require('../../config/log4js').logger('access');



exports.userlist = function(req, res){
	// var userid = tokenManager.getUserId(req);

	db.userModel.find({status:'1'}, function(err, list){
		return res.json({status:200, msg:'success', list:list});
	})


}


exports.signin = function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';

	db.userModel.findOne({username: username}, function (err, user) {
		if (err || null==user) {
			// 可添加安全登录次数校验
			return res.json({status:401, msg:'账号不存在，请先注册'});
		}
		user.comparePassword(password, function(isMatch) {
			if (!isMatch) {
				return res.json({status:401, msg:'账号或密码错误'});
            }
            var token = jwt.sign(user, secret.secretToken, {expiresIn: tokenManager.TOKEN_EXPIRATION }); //expiresIn: '24h'
            redisClient.set(token, '{is_expired:false}');
            redisClient.expire(token, tokenManager.TOKEN_EXPIRATION);
			return res.json({status:200, token:token});
		});

	});
};